<?php

namespace app\controllers;

use app\common\components\BaseWebController;
use app\common\service\captcha\ValidateCode;
use app\common\service\ConstantMapService;
use app\common\service\UtilService;
use app\models\sms\SmsCaptcha;
use app\common\service\AreaService;
use dosamigos\qrcode\QrCode;
use dosamigos\qrcode\lib\Enum;

class DefaultController extends BaseWebController
{

    public function actionIndex()
    {
        $this->layout = false;

        return $this->render('index');
    }

    private $captcha_cookies_name = "img_code";

    /**
     * 图形验证码
     */
    public function actionImg_captcha()
    {
        $font_path = \Yii::$app->getBasePath() . '/web/fonts/captcha.ttf';
        $captcha_handle = new ValidateCode($font_path);
        $captcha_handle->doimg();
        $this->setCookie($this->captcha_cookies_name, $captcha_handle->getCode());
    }


    public function actionGet_captcha()
    {
        // mobile: mobile,
//        img_captcha: img_captcha,
        $mobile = $this->post("mobile", "");
        $img_captcha = $this->post("img_captcha", "");

        if (!$mobile || !preg_match("/^1[0-9]{10}$/", $mobile)) {
            $this->removeCookie($this->captcha_cookies_name);
            return $this->renderJson([], "请输入符合要求的手机号码", -1);
        }

        $captcha_code = $this->getCookie($this->captcha_cookies_name);
        if (strtolower($img_captcha) != $captcha_code) {
            $this->removeCookie($this->captcha_cookies_name);
            return $this->renderJson([], "请输入正确的图形验证码", -1);
        }

        //手机验证码
        $model_sms = new SmsCaptcha();
        $model_sms->geneCustomerCaptcha($mobile, UtilService::getIP());
        $this->removeCookie($this->captcha_cookies_name);

        if ($model_sms) {
            return $this->renderJson([], "发送成功，请注意查收短信");
        }

        return $this->renderJson([], ConstantMapService::$default_syserror, -1);
    }

    public function actionQrcode()
    {
        $qr_code_url = $this->get("qr_code_url", "");
        header('Content-type: image/png');
        QrCode::png($qr_code_url, false, Enum::QR_ECLEVEL_H, 5, 0, false);
        exit();
    }

    public function actionCascade()
    {
        $province_id = $this->get('id', 0);
        $tree_info = AreaService::getProvinceCityTree($province_id);
        return $this->renderJSON($tree_info);
    }

    public function actionTest()
    {
    }
}
